package tech.mhuang.pacebox.core.area;

import tech.mhuang.pacebox.core.util.CollectionUtil;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 区域工具类
 *
 * @author mhuang
 * @since 1.1.2
 */
public class AreaUtil {

    /**
     * 区域处理
     *
     * @param address  处理的地址
     * @param areaList 区域列表
     * @param <T>      区域其他相关数据
     * @return 处理结果
     */
    public static <T> Area<T> process(final String address, List<Area<T>> areaList) {
        //匹配到省、可能会出现多个省的情况
        List<Area<T>> provinceList = areaList.stream().filter(areaInfo -> areaInfo.getCode().endsWith("0000") && address.contains(areaInfo.getName())).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(provinceList)) {
            //没有匹配到省获取市
            List<Area<T>> cityList = areaList.stream().filter(areaInfo -> areaInfo.getParentCode() != null && areaInfo.getCode().endsWith("00") && address.contains(areaInfo.getName())).collect(Collectors.toList());

            if (CollectionUtil.isEmpty(cityList)) {
                return null;
            }
            return areaList.stream().filter(areaInfo ->
                    cityList.stream().filter(city -> !city.getCode().equals(areaInfo.getCode()) &&
                            city.getCode().equals(areaInfo.getCode().substring(0, 4) + "00") &&
                            address.contains(areaInfo.getName())).count() > 0
            ).findFirst().orElse(cityList.get(0));

        } else {
            //取出匹配到省下市的和县/区
            List<Area<T>> cityAreaList = areaList.stream().filter(areaInfo ->
                    provinceList.stream().filter(province -> areaInfo.getParentCode() != null
                            && province.getCode().equals(areaInfo.getCode().substring(0, 2) + "0000")
                            && address.contains(areaInfo.getName())
                    ).count() > 0
            ).collect(Collectors.toList());
            if (cityAreaList.size() == 0) {
                return null;
            } else {
                return cityAreaList.stream().sorted(
                         Comparator.comparing(Area<T>::getCode).reversed()
                ).findFirst().get();
            }
        }
    }
}
